import React from 'react'
import style from './style'
import util from '../../util'
import cx from 'classnames'
import {FieldContainer, FieldBox} from '../form'

export default
class TreeList extends React.Component {

  constructor(props) {
    super(props)
    let value = props.placeholder || '选择父级部门...';
    if(Object.prototype.toString.call(props.value).slice(8,-1) === 'Array'){
      if(props.value.length){
        value = props.value.map(v => v.teamName).join(',');
      }
    }else{
      if(props.value && props.value.teamName)
        value = props.value.teamName;
    }
    const initCurObj = props.value || {};
    this.state = {
      active: false,
      cur: value,
    }
  }

  componentWillReceiveProps(props) {
    if (!util.isShallowEqual(this.props.value, props.value)) {
      let value = props.placeholder || '选择父级部门...';
      if(Object.prototype.toString.call(props.value).slice(8,-1) === 'Array'){
        if(props.value.length){
          value = props.value.map(v => v.teamName).join('，');
        }
      }else{
        if(props.value && props.value.teamName)
          value = props.value.teamName;
      }
      this.setState({
        cur: value
      })
    }
  }

  bindClick = (e) => {
    let el = e.target
    while(el && el !== document.body && !~el.className.indexOf(style.root)) {
      el = el.parentNode
    }

    if (el && el === document.body) {
      this.setState({
        active: false
      })
      this.unbind()
    }
  }

  unbind() {
    util.unbind(document, 'click', this.bindClick)
  }

  componentWillUnmount() {
    this.unbind()
  }

  toggleTree(e) {
    const curActive = this.state.active
    this.setState({
      active: !this.state.active
    })
    if (!curActive) {
      util.bind(document, 'click', this.bindClick)
    }
  }

  handleClick(e, item) {
    const {
      mulit
    } = this.props;
    if(mulit) {
      return;
    };
    const cur = e.target.textContent
    e.stopPropagation()
    this.props.onClick(item)
    this.setState({
      active: false,
      cur
    })
    this.unbind()
  }
  handleMulClick = (e, item) => {
    e.stopPropagation()
    const flag = e.target.checked;
    const {
      value,
      root
    } = this.props;
    if(flag){
      const cleanList = [];
      const cleanFn = (team) => {
        const cleanItem = value.find(v => v.teamId === team.teamId);
        if(cleanItem)
          cleanList.push(cleanItem);
        if(team.teams)
          team.teams.map(v => cleanFn(v))
      } 
      cleanFn(item);
      this.props.onClick([...value.filter(v => !~cleanList.findIndex(f => v.teamId === f.teamId)), item]);
    }else{
      this.props.onClick(value.filter(v => v.teamId !== item.teamId))
    }
  }
  ulClick = (e) => {
    const {
      mulit
    } = this.props;
    if(mulit) {
      e.stopPropagation()
    };
  }
  render() {
    const { root,value } = this.props
    const { mulit,disabled, required,placeholder, multi,type='text', width,attr, name, regex, className, label, error, bubbleList, ...others } = this.props

    if (!root) return null
    const render = (team, flag) => team.teams? (
      <ul onClick={this.ulClick}>
        {
          team.teams.map((item, i) => {
            let isCheck = flag;
            if(mulit && !flag)
              isCheck = !!~value.findIndex(v => v.teamId === item.teamId );
            return (
              <li key={i} onMouseDown={e => this.handleClick(e, item)}>
                <span>
                {
                  mulit ?
                  <input type="checkbox" checked={isCheck} disabled={flag} onChange={e => this.handleMulClick(e, item)}/>
                  : null
                }
                { item.teamName }</span>
                { render(item, isCheck) }
              </li>
            )
          })
        }
     </ul>
    ): null
    return (
      <FieldBox
        label={label}
        name={name}
        required={required}
      >
        <FieldContainer
          hasBox={true}
          active={this.state.active}
          error={this.state.error}
          disabled={disabled}
          msg={this.state.msg}
          className={className}
          bubbleList={bubbleList}
          width={width}
        >
          <div 
            data-role="tree-list"
            className={cx(style.root, {
              [this.props.className]: this.props.className
            })} 
            onClick={::this.toggleTree}
          >
            <span>{ this.state.cur }</span>
            { this.state.active? render(root): null }
            {/*
              this.props.required && <span className={style.required}>必选</span>
            */}
          </div>
        </FieldContainer>
      </FieldBox>
     
    )
  }
}
